{% extends 'base.html' %}
{% load static %}

{% block title %}数据备份管理 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    .backup-card {
        background: white;
        border-radius: 10px;
        padding: 25px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        transition: all 0.3s;
    }
    
    .backup-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    }
    
    .section-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 15px 20px;
        border-radius: 10px 10px 0 0;
        margin: -25px -25px 20px -25px;
    }
    
    .backup-status {
        padding: 4px 12px;
        border-radius: 15px;
        font-size: 0.85em;
        font-weight: bold;
    }
    
    .status-pending { background: #fff3cd; color: #856404; }
    .status-running { background: #cce5ff; color: #004085; }
    .status-completed { background: #d4edda; color: #155724; }
    .status-failed { background: #f8d7da; color: #721c24; }
    
    .backup-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 8px;
        margin-bottom: 15px;
    }
    
    .backup-actions {
        display: flex;
        gap: 10px;
    }
    
    .file-size {
        color: #6c757d;
        font-size: 0.9em;
    }
    
    .progress-container {
        margin-top: 10px;
    }
    
    .backup-type-full { color: #007bff; }
    .backup-type-incremental { color: #28a745; }
    .backup-type-manual { color: #ffc107; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-database"></i> 数据备份管理</h2>
                <div>
                    <a href="{% url 'assets:create_backup' %}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 创建备份
                    </a>
                    <button class="btn btn-outline-info" onclick="checkBackupStatus()">
                        <i class="fas fa-sync-alt"></i> 刷新状态
                    </button>
                </div>
            </div>
            
            <!-- 备份统计 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="backup-card text-center">
                        <h3 class="text-primary">{{ page_obj.paginator.count }}</h3>
                        <p class="mb-0">总备份数</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="backup-card text-center">
                        <h3 class="text-success">
                            {{ page_obj.object_list|length }}
                        </h3>
                        <p class="mb-0">已完成</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="backup-card text-center">
                        <h3 class="text-info">0</h3>
                        <p class="mb-0">进行中</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="backup-card text-center">
                        <h3 class="text-warning">0</h3>
                        <p class="mb-0">失败</p>
                    </div>
                </div>
            </div>
            
            <!-- 备份列表 -->
            <div class="backup-card">
                <div class="section-header">
                    <h5><i class="fas fa-list"></i> 备份记录</h5>
                </div>
                
                {% for backup in page_obj %}
                <div class="backup-info">
                    <div class="flex-grow-1">
                        <div class="d-flex align-items-center mb-2">
                            <h6 class="mb-0 me-3">{{ backup.name }}</h6>
                            <span class="backup-status status-{{ backup.status }}">
                                {{ backup.get_status_display }}
                            </span>
                            <span class="badge backup-type-{{ backup.backup_type }} ms-2">
                                {{ backup.get_backup_type_display }}
                            </span>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted">
                                    <i class="fas fa-calendar"></i> 创建时间: {{ backup.created_at|date:"Y-m-d H:i:s" }}
                                </small>
                                {% if backup.completed_at %}
                                    <br><small class="text-muted">
                                        <i class="fas fa-check"></i> 完成时间: {{ backup.completed_at|date:"Y-m-d H:i:s" }}
                                    </small>
                                {% endif %}
                            </div>
                            <div class="col-md-6">
                                {% if backup.file_size %}
                                    <small class="file-size">
                                        <i class="fas fa-file"></i> 文件大小: {{ backup.file_size_mb }} MB
                                    </small>
                                {% endif %}
                                {% if backup.duration %}
                                    <br><small class="text-muted">
                                        <i class="fas fa-clock"></i> 耗时: {{ backup.duration }}
                                    </small>
                                {% endif %}
                            </div>
                        </div>
                        
                        {% if backup.description %}
                            <div class="mt-2">
                                <small class="text-muted">{{ backup.description }}</small>
                            </div>
                        {% endif %}
                        
                        {% if backup.error_message %}
                            <div class="mt-2">
                                <small class="text-danger">
                                    <i class="fas fa-exclamation-triangle"></i> {{ backup.error_message }}
                                </small>
                            </div>
                        {% endif %}
                        
                        {% if backup.status == 'running' %}
                            <div class="progress-container">
                                <div class="progress">
                                    <div class="progress-bar progress-bar-striped progress-bar-animated" 
                                         role="progressbar" style="width: 45%">
                                        备份进行中...
                                    </div>
                                </div>
                            </div>
                        {% endif %}
                    </div>
                    
                    <div class="backup-actions">
                        {% if backup.status == 'completed' and backup.file_path %}
                            <button class="btn btn-sm btn-success" onclick="downloadBackup('{{ backup.id }}')">
                                <i class="fas fa-download"></i> 下载
                            </button>
                            <button class="btn btn-sm btn-info" onclick="restoreBackup('{{ backup.id }}')">
                                <i class="fas fa-undo"></i> 恢复
                            </button>
                        {% endif %}
                        
                        {% if backup.status in 'pending,failed' %}
                            <button class="btn btn-sm btn-warning" onclick="retryBackup('{{ backup.id }}')">
                                <i class="fas fa-redo"></i> 重试
                            </button>
                        {% endif %}
                        
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteBackup('{{ backup.id }}')">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
                {% empty %}
                <div class="text-center text-muted py-5">
                    <i class="fas fa-database fa-3x mb-3"></i>
                    <p>暂无备份记录</p>
                    <a href="{% url 'assets:create_backup' %}" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 创建第一个备份
                    </a>
                </div>
                {% endfor %}
                
                <!-- 分页 -->
                {% if page_obj.has_other_pages %}
                <div class="d-flex justify-content-center mt-4">
                    <nav>
                        <ul class="pagination">
                            {% if page_obj.has_previous %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}">上一页</a>
                                </li>
                            {% endif %}
                            
                            {% for num in page_obj.paginator.page_range %}
                                {% if page_obj.number == num %}
                                    <li class="page-item active">
                                        <span class="page-link">{{ num }}</span>
                                    </li>
                                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                    <li class="page-item">
                                        <a class="page-link" href="?page={{ num }}">{{ num }}</a>
                                    </li>
                                {% endif %}
                            {% endfor %}
                            
                            {% if page_obj.has_next %}
                                <li class="page-item">
                                    <a class="page-link" href="?page={{ page_obj.next_page_number }}">下一页</a>
                                </li>
                            {% endif %}
                        </ul>
                    </nav>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 恢复确认模态框 -->
<div class="modal fade" id="restoreModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle text-warning"></i> 确认恢复
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <strong>警告：</strong>恢复操作将覆盖当前数据，此操作不可逆！
                </div>
                <p>您确定要从此备份恢复数据吗？</p>
                <p><strong>备份信息：</strong></p>
                <ul id="backupInfo">
                    <!-- 备份信息将在这里显示 -->
                </ul>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmRestoreBtn">确认恢复</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 自动刷新进行中的备份状态
    setInterval(function() {
        if ($('.status-running, .status-pending').length > 0) {
            checkBackupStatus();
        }
    }, 10000); // 每10秒检查一次
});

// 检查备份状态
function checkBackupStatus() {
    // 这里可以通过AJAX获取最新的备份状态
    // 暂时只是刷新页面
    location.reload();
}

// 下载备份
function downloadBackup(backupId) {
    window.location.href = `/assets/system/backups/${backupId}/download/`;
}

// 恢复备份
function restoreBackup(backupId) {
    // 显示确认模态框
    $('#restoreModal').modal('show');
    
    // 设置确认按钮的点击事件
    $('#confirmRestoreBtn').off('click').on('click', function() {
        $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 恢复中...');
        
        $.ajax({
            url: `/assets/system/backups/${backupId}/restore/`,
            method: 'POST',
            data: {
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            success: function(response) {
                if (response.success) {
                    showAlert('success', '数据恢复成功，页面将自动刷新');
                    setTimeout(function() {
                        location.reload();
                    }, 2000);
                } else {
                    showAlert('error', response.message || '恢复失败');
                }
            },
            error: function() {
                showAlert('error', '恢复失败，请重试');
            },
            complete: function() {
                $('#restoreModal').modal('hide');
                $('#confirmRestoreBtn').prop('disabled', false).html('确认恢复');
            }
        });
    });
}

// 重试备份
function retryBackup(backupId) {
    if (!confirm('确定要重试此备份吗？')) {
        return;
    }
    
    $.ajax({
        url: `/assets/system/backups/${backupId}/retry/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                showAlert('success', '备份已重新开始');
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                showAlert('error', response.message || '重试失败');
            }
        },
        error: function() {
            showAlert('error', '重试失败，请重试');
        }
    });
}

// 删除备份
function deleteBackup(backupId) {
    if (!confirm('确定要删除此备份吗？此操作不可逆！')) {
        return;
    }
    
    $.ajax({
        url: `/assets/system/backups/${backupId}/delete/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                showAlert('success', '备份已删除');
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                showAlert('error', response.message || '删除失败');
            }
        },
        error: function() {
            showAlert('error', '删除失败，请重试');
        }
    });
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    // 3秒后自动消失
    setTimeout(function() {
        $('.alert').alert('close');
    }, 3000);
}
</script>
{% endblock %}